# -*- coding: utf-8 -*-

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.support.wait import WebDriverWait
from Resources import UserName
import unittest, time, re
from LbtFront.Base.LoginPage import login
from DriverAndUnit import myunit,myfunction
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

'''订购和积分和财务管理'''
class Pc(myunit.myTest,login):
    def test_dinggouForStudent(self):
        '''订购管理'''
        try:
            driver = self.driver
            self.login_true()
            driver.find_element_by_link_text(u"订购管理").click()

            driver.find_element_by_xpath("//a[contains(@href,'getStudentOrdList.jhtml')]").click()

            time.sleep(2)
            # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | iframe | ]]
            orderStudentFrame = driver.find_element_by_xpath("//iframe[contains(@src,'getStudentOrdList.jhtml')]")
            self.driver.switch_to.frame(orderStudentFrame)

            # driver.find_element_by_css_selector("button.btn.btn-primary").click()
            driver.find_element_by_xpath('//div[@id="opercode_chosen"]').click()
            driver.find_element_by_xpath('//li[@class="active-result" and @data-option-array-index="2"]').click()
            driver.find_element_by_id("phone").clear()
            driver.find_element_by_id("phone").send_keys(UserName.orderPhone)
            # driver.find_element_by_css_selector("button.btn.btn-primary").click()
            driver.find_element_by_xpath('//button[@class="btn btn-primary"]').click()
            driver.find_element_by_xpath("(//button[@type='button'])[4]").click()
            driver.find_element_by_id("aPrice").click()
            driver.find_element_by_id("sncode").clear()
            driver.find_element_by_id("sncode").send_keys(UserName.orderPhone)
            # driver.find_element_by_css_selector("button.btn.btn-primary").click()
            driver.find_element_by_xpath('//a[@class="layui-layer-btn0"]').click()
            time.sleep(3)

            driver.find_element_by_id("phone").clear()
            driver.find_element_by_id("phone").send_keys("13598411889")
            driver.find_element_by_xpath('//button[@class="btn btn-primary"]').click()

            studentName = driver.find_element_by_xpath(
                "//table[@class='table table-bordered table-hover table-wrap']/tbody/tr[1]/td[2]").text
            studentClassName = driver.find_element_by_xpath(
                "//table[@class='table table-bordered table-hover table-wrap']/tbody/tr[1]/td[3]").text
            className = str(str(studentClassName).split("(")[0])
            '''
            studentName='王小伟'
            '''
            time.sleep(3)
            driver.find_element_by_xpath("//a[@href='child_smsOrder.jhtml']").click()
            driver.find_element_by_xpath("//input[@name='orderPlan' and @value='A']").click()
            # driver.find_element_by_css_selector("div.radio > label").click()
            driver.find_element_by_xpath("//button[@class='btn btn-primary btn-block addChild']").click()
            time.sleep(2)
            self.driver.switch_to.frame('layui-layer-iframe1')
            '''选中订购学生
            1、展开所有班级。
            2、查看所有未订购的学生。
            3、选中符合条件的学生。
            '''
            classs = driver.find_elements_by_xpath("//span[@class='class-name' and @href!='None']")
            isBreak = False
            for classcurrent in classs:
                classcurrent.click()
                classcurrent.click()
                currentClassname = str(str(classcurrent.text).split("(")[0])
                if currentClassname.strip()==className.strip():
                    classcurrent.click()
                    eduStr = str(driver.find_element_by_xpath(
                        "//span[@class='class-name' and @class!='collapsed' and @href!='None']/small/span").get_attribute(
                        "class"))
                    eduId = eduStr.split("_")[1]
                    students = driver.find_elements_by_xpath("//input[@data='1' and @data_dept='" + eduId + "']")
                    for student in students:
                        if student.get_attribute("name") == studentName:
                            student.click()
                            isBreak = True
                            break
                    classcurrent.click()
                    if isBreak == True:
                        break
            '''
            for classCurrent in classs:
                # pc端的一个bug，进去页面是关闭的，但是属性是打开的
                classCurrent.click()
                classCurrent.click()
                if classCurrent.get_attribute("href") != None and "collapsed" in str(
                        classCurrent.get_attribute("class")):
                    classCurrent.click()
                eduStr = str(driver.find_element_by_xpath(
                    "//span[@class='class-name' and @class!='collapsed' and @href!='None']/small/span").get_attribute(
                    "class"))
                eduId = eduStr.split("_")[1]
                #print(eduId)
                students = driver.find_elements_by_xpath("//input[@data='1' and @data_dept='" + eduId + "']")
                for student in students:
                    if student.get_attribute("name") == studentName:
                        student.click()
                        isBreak = True
                        break
                classCurrent.click()
                if isBreak == True:
                    break
            '''
            # driver.find_element_by_xpath("//input[@data='1' and @name='"+studentName+"']").click()
            self.driver.switch_to.parent_frame()
            # ERROR: Caught exception [ERROR: Unsupported command [selectWindow | name=iframe | ]]
            driver.find_element_by_link_text(u"提交").click()
            # WebDriverWait(driver,20,0.5).until(lambda x: x.find_element_by_xpath("//button[@id='buttonOrd']")).click()

            driver.find_element_by_id("buttonOrd").click()

            time.sleep(2)
            driver.find_element_by_link_text(u"验证码订购").click()
            """
            '''重点：操作windows对象，
            1、在操作前先定位当前window对象current_window = driver.current_window_handle
            2、进行操作，弹出第二个window对象
            3、获取所有window对象all_windows = driver.window_handles 
            4、找到不是老窗口的新窗口。然后进行操作。
                    for window in all_windows:
                if window != current_window:
                    driver.switch_to.window(window)
            5、操作完后，切回去。driver.switch_to.window(current_window)
            -----------------低版本火狐浏览器获取不到句柄------------------
            坑爹！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
            -----------------高版本implicit_wait全局等待不能用-------------
            '''

            特别说明：
                    for window in all_windows:
                if window != current_window:
                    oldwindow=window
                    driver.switch_to.window(oldwindow)
                    driver.close()
            driver.close()关闭当前window窗口
            driver.quit()关闭当前窗口关联的所有窗口
            """
            current_window = driver.current_window_handle  # 获取当前窗口handle name
            WebDriverWait(driver, 20, 0.5).until(lambda x: x.find_element_by_link_text(u"《验证码批量导入模板》")).click()
            # driver.find_element_by_link_text(u"《验证码批量导入模板》").click()
            time.sleep(10)
            '''切换到windows对象'''
            # driver.find_element_by_link_text('Window Open Test With Title').click()
            all_windows = driver.window_handles  # 获取所有窗口handle name

            # 切换window，如果window不是当前window，则切换到该window
            for window in all_windows:
                if window != current_window:
                    oldwindow = window
                    #print(oldwindow.title())  # 打印该页面title
                    #print("-----------------")
                    #print(current_window.title())
                    #print("-----------------")
                    driver.switch_to.window(oldwindow)
                    driver.close()
            driver.switch_to.window(current_window)
            self.driver.switch_to.parent_frame()
        finally:
            errorPng = "FinallyPng_" + myfunction.getCurrentTime() + ".png"
            myfunction.insert_img(self.driver, errorPng)
    def test_dinggouForTeacher(self):
        '''老师订购'''
        try:
            driver = self.driver
            self.login_true()
            driver.find_element_by_link_text(u"订购管理").click()

            driver.find_element_by_link_text(u"教职工订购").click()
            time.sleep(3)
            orderTeacherFrame = driver.find_element_by_xpath("//iframe[contains(@src,'getTeacherOrdList.jhtml')]")
            driver.switch_to.frame(orderTeacherFrame)
            driver.find_element_by_link_text(u"短信订购").click()
            self.driver.switch_to.parent_frame()

            driver.find_element_by_link_text(u"订购统计").click()
            orderTeacherFrame = driver.find_element_by_xpath("//iframe[contains(@src,'ordEduCount.jhtml')]")
            driver.switch_to.frame(orderTeacherFrame)
            self.driver.switch_to.parent_frame()
        finally:
            errorPng = "FinallyPng_" + myfunction.getCurrentTime() + ".png"
            myfunction.insert_img(self.driver, errorPng)

    def test_jifen(self):
        '''积分和订购'''
        try:
            driver = self.driver
            self.login_true()
            '''
            driver.get(self.base_url + "/index.jhtml")
            #driver.find_element_by_link_text(u"幼儿园管理").click()
            driver.find_element_by_xpath("//a[contains(@href,'login.jhtml')]").click()
            #driver.find_element(By.XPATH("//a[ends-with(@href,'login.jhtml')]")).click()
            driver.find_element_by_id("password").clear()
            driver.find_element_by_id("password").send_keys("222222")
            driver.find_element_by_id("username").clear()
            driver.find_element_by_id("username").send_keys("13598411889")
            driver.find_element_by_id("btnLogin").click()
            driver.find_element_by_css_selector("button.btn_rolse").click()
            '''
            '''积分明细'''
            driver.find_element_by_xpath("//i[@class='icon-integral']").click()
            # driver.find_element_by_link_text(u"积分明细").click()
            driver.find_element_by_xpath("//a[contains(@href,'toMonthDetail.jhtml')]").click()
            # driver.switch_to.frame("iframe12")
            jifenDetail = driver.find_element_by_xpath("//iframe[contains(@src,'toMonthDetail.jhtml')]")
            driver.switch_to.frame(jifenDetail)
            time.sleep(3)
            driver.find_element_by_xpath(
                "//a[@href='http://www.lebeitong.com:80/html/integral/integralRule.html']").click()
            # driver.find_element_by_xpath("//*[contains(@href,'integralRule.jhtml')]").click()
            driver.find_element_by_xpath("//a[contains(@href,'toMonthDetail.jhtml')]").click()
            driver.find_element_by_xpath("//button[@class='btn-init text-primary teacherIntegralDetail'][1]").click()
            driver.find_element_by_xpath("//a[@class='layui-layer-ico layui-layer-close layui-layer-close1']").click()
            time.sleep(1)
            driver.find_elements_by_xpath("//button[@class='btn-init text-primary teacherIntegralDetail']")[1].click()
            time.sleep(1)
            driver.find_element_by_xpath("//a[@class='layui-layer-ico layui-layer-close layui-layer-close1']").click()
            driver.switch_to.parent_frame()
            # ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]]
            '''分配积分'''
            driver.find_element_by_xpath("//a[contains(@href,'toIntegralAllot.jhtml')]").click()
            integralAllot = driver.find_element_by_xpath("//iframe[contains(@src,'toIntegralAllot.jhtml')]")
            driver.switch_to.frame(integralAllot)
            # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | iframe | ]]
            # driver.find_element_by_link_text(u"分配记录").click()
            driver.find_element_by_xpath("//a[contains(@href,'toIntegraldistriRecord.jhtml')]").click()
            driver.find_element_by_id("lasttmouth").click()
            driver.find_element_by_id("doulasttmouth").click()
            driver.switch_to.parent_frame()

            '''财务管理'''
            # ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]]
            driver.find_element_by_xpath("//i[@class='icon-finance']").click()
            time.sleep(1)
            driver.find_element_by_xpath("//a[contains(@href,'studentCharge.jhtml')]").click()
            manageCharge = driver.find_element_by_xpath("//iframe[contains(@src,'studentCharge.jhtml')]")
            driver.switch_to.frame(manageCharge)
            # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | iframe | ]]
            driver.find_element_by_link_text(u"学生收费导入").click()
            driver.find_element_by_link_text(u"教职工收费导入").click()
            driver.find_element_by_link_text(u"教职工收费").click()
            driver.find_element_by_link_text(u"学生收费").click()
            # 此处应该进行收费的增删改查操作。
            driver.switch_to.parent_frame()
            # ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]]
            driver.find_element_by_link_text(u"支出管理").click()
            spendingManage = driver.find_element_by_xpath("//iframe[contains(@src,'spendingManage.jhtml')]")
            driver.switch_to.frame(spendingManage)
            # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | iframe | ]]
            # 此处应该有支出项的增删改查
            driver.switch_to.parent_frame()
            # ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]]
            driver.find_element_by_link_text(u"财务统计").click()
            queryChildIncomeList = driver.find_element_by_xpath(
                "//iframe[contains(@src,'queryChildIncomeList.jhtml')]")
            driver.switch_to.frame(queryChildIncomeList)
            # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | iframe | ]]
            driver.find_element_by_link_text(u"教职工收费统计").click()
            driver.find_element_by_link_text(u"支出统计").click()
        finally:
            errorPng = "FinallyPng_" + myfunction.getCurrentTime() + ".png"
            myfunction.insert_img(self.driver, errorPng)

    def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e:
            return False
        return True

    def is_alert_present(self):
        try:
            self.driver.switch_to_alert()
        except NoAlertPresentException as e:
            return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally:
            self.accept_next_alert = True
    '''
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
    '''

if __name__ == "__main__":
    unittest.main()
